package com.dwjm.controller;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Decoder;

import com.dwjm.common.FileBaseController;

/**
 * 上传图片Controller
 * 
 * @author luans
 * @date 2016年12月26日
 */
@Controller
@Scope(value="prototype")
@SuppressWarnings("restriction")
@RequestMapping("imageController")
public class ImageController extends FileBaseController {
	

	/**
	 * 上传图片:单张图片上传（jquery）
	 * 
	 * @param HttpServletRequest
	 * @param String
	 * @return String:图片保存路径
	 * @date 2016年12月26日
	 * @auther luans
	 */
	@RequestMapping("updateImg")
	@ResponseBody
	public String updateImg(HttpServletRequest request, String image,String oldImg,String path) {
		String marker = image.substring(image.indexOf("/") + 1,
				image.indexOf(";"));
		String header = "data:image/" + marker + ";base64,";
		String image1 = image.substring(header.length());
		BASE64Decoder decoder = new BASE64Decoder();
		String rootpath = request.getSession().getServletContext()
				.getRealPath(System.getProperty("file.separator"));
		System.out.println("rootpath1:"+rootpath);
		rootpath=rootpath.substring(0,rootpath.length()-13);//去掉"fourmSystem\",直接保存到服务器的webapp目录下，和项目同级目录
		System.out.println("rootpath2:"+rootpath);
		String uploadpath = rootpath + path;
		System.out.println("rootpath3:"+rootpath);
		File uploadPath = new File(uploadpath);
		String fileName =super.getFileNameNew() + "." + marker;// 图片名字
		if (!uploadPath.exists()) {
			uploadPath.mkdirs();
		}
		String imgFilePath = uploadpath + System.getProperty("file.separator")
				+ fileName;
		String name = imgFilePath.substring(imgFilePath.lastIndexOf("\\") + 1,
				imgFilePath.length());//
		try {
			byte[] decodedBytes = decoder.decodeBuffer(image1);
			FileOutputStream out = new FileOutputStream(imgFilePath);
			out.write(decodedBytes);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//删除之前的图片
		File f = new File(rootpath + path+oldImg);
		f.delete();
		return fileName;
	}

	 

}
